using MapsterMapper;
using AiQiuQuan.Sport.Model.Models;
using AiQiuQuan.Sport.Core;
using AiQiuQuan.Sport.WebApi.Entities;
using AiQiuQuan.Sport.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;

namespace AiQiuQuan.Sport.WebApi.Services.Impl
{
    /// <summary>
    /// 用户积分管理
    /// </summary>
    public class BaseUserPointService : IBaseUserPointService
    {
        private readonly IMapper _mapper;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IBaseUserPointRepository _baseUserPointRepository;
        private readonly IBaseUserPointRecordRepository _baseUserPointRecordRepository;

        /// <summary>
        /// ctor
        /// </summary>
        public BaseUserPointService(
            IMapper mapper,
            IUnitOfWorkManager unitOfWorkManager,
            IBaseUserPointRepository baseUserPointRepository,
            IBaseUserPointRecordRepository baseUserPointRecordRepository)
        {
            _mapper = mapper;
            _unitOfWorkManager = unitOfWorkManager;
            _baseUserPointRepository = baseUserPointRepository;
            _baseUserPointRecordRepository = baseUserPointRecordRepository;
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public async Task<BaseUserPointDto> GetAsync(Guid id)
        {
            var baseUserPoint = await _baseUserPointRepository.FirstOrDefaultAsync(m => m.ID == id);
            return _mapper.Map<BaseUserPoint, BaseUserPointDto>(baseUserPoint);
        }

        /// <summary>
        /// 新增积分记录
        /// </summary>
        public async Task<UnaryResult> AddRecordAsync(List<BaseUserPointRecordAddDto> request)
        {
            var addPoinRecordList = new List<BaseUserPointRecord>();
            var addPoinList = new List<BaseUserPoint>();
            var updatePoinList = new List<BaseUserPoint>();

            var groupRecordList = request.GroupBy(m => m.UserId);
            foreach (var groupRecord in groupRecordList)
            {
                //用户积分
                var userPoint = await _baseUserPointRepository.FirstOrDefaultAsync(m => m.UserId == groupRecord.Key);
                var tempPoint = 0L;
                var pointId = Guid.NewGuid();
                //积分用户不存在时
                if (userPoint == null)
                {
                    userPoint = new BaseUserPoint
                    {
                        ID = pointId,
                        UserId = groupRecord.Key,
                        Point = groupRecord.Sum(m => m.ChangePoint)
                    };
                    addPoinList.Add(userPoint);
                }
                else
                {
                    pointId = userPoint.ID;
                    tempPoint = userPoint.Point;
                    userPoint.Point += groupRecord.Sum(m => m.ChangePoint);
                    updatePoinList.Add(userPoint);
                }

                foreach (var item in groupRecord)
                {
                    tempPoint += item.ChangePoint;
                    var pointRecord = _mapper.Map<BaseUserPointRecord>(item);
                    pointRecord.UserPointId = pointId;
                    pointRecord.RemainPoint = tempPoint;
                    pointRecord.CreateTime = DateTimeOffset.Now;
                    addPoinRecordList.Add(pointRecord);
                    if (groupRecord.Count() >= 2)
                    {
                        await Task.Delay(100);
                    }
                }
            }

            using (var uow = _unitOfWorkManager.Begin())
            {
                await _baseUserPointRecordRepository.BulkAddAsync(addPoinRecordList);
                if (addPoinList.Any())
                {
                    await _baseUserPointRepository.BulkAddAsync(addPoinList);
                }

                foreach (var item in updatePoinList)
                {
                    await _baseUserPointRepository.UpdateAsync(item);
                }

                await uow.CompleteAsync();
            }

            return UnaryResult.Succeed();
        }

        /// <summary>
        /// 修改
        /// </summary>
        public async Task<UnaryResult> UpdateAsync(BaseUserPointUpdateDto model)
        {
            var baseUserPoint = await _baseUserPointRepository.FirstOrDefaultAsync(m => m.ID == model.ID);
            _mapper.Map(model, baseUserPoint);
            await _baseUserPointRepository.UpdateAsync(baseUserPoint);

            return UnaryResult.Succeed();
        }

        /// <summary>
        /// 删除
        /// </summary>
        public async Task<UnaryResult> DeleteAsync(Guid id)
        {
            await _baseUserPointRepository.DeleteAsync(p => p.ID == id);
            return UnaryResult.Succeed();
        }
    }
}
